#encoding=utf-8
'''
Created on 2015-3-29

@author: cooler
'''
import sys,os
reload(sys)
sys.setdefaultencoding('utf8')

import  logging,  os.path
import math, time
from datetime import datetime, timedelta
import math,re
import traceback
import hashlib
import base64
from werkzeug import secure_filename

from flask import Blueprint, render_template, make_response, request, redirect,url_for, session, abort, current_app
from flask import g,jsonify
from flask_principal import Principal, Permission, UserNeed, RoleNeed, Identity, AnonymousIdentity, identity_changed, identity_loaded

from service.auth import user
from service.authority import *
from service.models import *
from utils.CheckSign import init_salt,init_password,init_api_key,init_secret_key

logger = logging.getLogger('user')
logger.setLevel(logging.DEBUG)


@user.route('/test/', methods=['GET'])
def test():
    userinfo = session.get('userinfo')
    logger.info("user logout: account - %s, roles- %s" % (session.get("userinfo").get("account"), session.get("userinfo").get("roles")))
    return jsonify(userinfo)

@user.route('/', methods=['GET'])
def index():
    return jsonify(g.results)

@user.route('/login', methods=['GET'])
def login():
    return render_template('/user/login.html')

@user.route('/register', methods=['GET'])
def register():
    return render_template('/user/register.html')


@user.route("/auth", methods=['GET', 'POST'])
def auth():
    try:
        username = g.args.get('username').strip()
        password = g.args.get('password').strip()
        logger.info(username)
        logger.info(password)
        user_info = User_info.objects(username=username).first()
        if user_info:
            right_password = init_password(password,user_info['salt'])
            if user_info['password'] == right_password:
                if user_info['role'] < 10:
                    roles = ['admin']
                else:
                    roles = ['operator']
                userinfo = dict()
                userinfo['account'] = username
                userinfo['roles'] = roles
                session["userinfo"] = userinfo
                identity_changed.send(current_app._get_current_object(), identity=Identity(userinfo['account']))
                logger.info("user login: account - %s, roles- %s" %
                            (session.get("userinfo").get("account"), session.get("userinfo").get("roles")))
                g.results['msg']= "success" 
                g.results['datas']['code'] = 1
            else:
                g.results['msg'] = "password error"
                g.results['datas']['code'] = 2
        else:
            g.results['msg'] = "please regist first !"
            g.results['datas']['code'] = 3
        return jsonify(g.results)
 
    except Exception as e:
        logger.error(traceback.format_exc(e))
        g.results['datas']['code'] = 3
        g.results['msg'] = str(e)
        return jsonify(g.results)

@user.route("/logout", methods=['GET'])
def logout():
    if session.get('userinfo') is not None:
        logger.info("user logout: account - %s, roles- %s" % (
            session.get("userinfo").get("account"), session.get("userinfo").get("roles")))
        session.pop("userinfo")
        # Remove session keys set by Flask-Principal
        for key in ('identity.name', 'identity.auth_type'):
            session.pop(key, None)

        # Tell Flask-Principal the user is anonymous
        identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity())
    return redirect('/user/login')


@user.route('/add_user', methods=['GET','POST'])
def add_user():
    username = g.args.get("username","").strip()
    password = g.args.get("password","").strip()
    phone = g.args.get("phone","").strip()
    email = g.args.get("email","").strip()
    account = User_info.objects(username=username).first()
    if account:
        g.results['datas']["code"]=2
        g.results['msg']='{0} has been register！'.format(username)
    else:        
        salt = init_salt()
        account = User_info()
        account.salt = salt
        account.password = init_password(password,salt)
        account.username=username
        account.phone=phone
        account.email=email
        account.role=5
        account.api_key=init_api_key()
        account.secret_key=init_secret_key()
        account.save()
    return jsonify(g.results)

@user.route('/modify_pwd', methods=['GET','POST'])
@admin_permission.require(http_exception=401)
def modify_pwd():
    username = g.args.get("username","").strip()
    password = g.args.get("password","").strip()
    salt = init_salt()
    account = User_info()
    account.salt = salt
    account.password = init_password(password,salt)
    account.username=username
    account.role=5
    account.api_key=init_api_key()
    account.secret_key=init_secret_key()
    # account.save()
    # g.results['datas']["user"]=account
    return jsonify(g.results)








